package ai.people.core.security.extractor;

import ai.people.core.security.entity.AuthenticationUser;
import ai.people.core.common.authenticate.AuthenticatedUserExtraction;
import ai.people.netmon.utils.StringPool;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * @author yuanqinglong
 * @date 2022/7/11 17:55
 */
public class AuthenticatedUsername implements AuthenticatedUserExtraction {


    /**
     * 经过身份验证用户名
     *
     * @return {@link String}
     */
    @Override
    public String authenticatedUsername() {
        return Optional.ofNullable(SecurityContextHolder.getContext())
                .map(SecurityContext::getAuthentication).map(authentication -> (AuthenticationUser) authentication.getPrincipal()).map(AuthenticationUser::getUsername).orElse(StringPool.EMPTY);
    }
}
